package com.itheima.health.service.impl;

import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderSettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

@Service
@Slf4j
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    public List<Map> getOrderSettingByMonth(Integer year, Integer month) {
        LocalDate begin = LocalDate.of(year, month, 1);
        LocalDate end = begin.with(TemporalAdjusters.lastDayOfMonth());
        List<OrderSetting> orderSettingList=orderSettingDao.getOrderSettingByMonth(begin,end);
        List<Map> mapList  = new ArrayList<>();
        for (OrderSetting orderSetting : orderSettingList) {
            Calendar calendar = Calendar.getInstance();
            Date orderDate = orderSetting.getOrderDate();
            calendar.setTime(orderDate);
            Map map = new HashMap<>();
            map.put("date",calendar.get(Calendar.DAY_OF_MONTH));
            map.put("number",orderSetting.getNumber());
            map.put("reservations",orderSetting.getReservations());
            mapList.add(map);


        }
        return mapList;

    }

    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        //先查询有数据执行更新操作
        Date orderDate = orderSetting.getOrderDate();
        OrderSetting orderSetting1=orderSettingDao.getOrderSettingByMonthAndDay(orderDate);
        if (orderSetting1 ==null){
            orderSettingDao.insert(orderSetting);
        }else{
            Integer id = orderSetting1.getId();
            orderSetting.setId(id);
            orderSettingDao.edit(orderSetting);
        }
    }

    @Override
    public void insert(List<OrderSetting> orderSettingList) {
      if (orderSettingList !=null&& orderSettingList.size()>0){
          for (OrderSetting orderSetting : orderSettingList) {
              Integer count=orderSettingDao.findCountByDate(orderSetting.getOrderDate());
              if (count>0){
                  //已经存在
                  orderSettingDao.edit(orderSetting);
              }
              else {
                  orderSettingDao.insert(orderSetting);
              }
          }
      }
    }
}
